import { useDispatch, useSelector } from 'react-redux';
import {
  Redirect,
  Route, Switch, useHistory, useRouteMatch,
} from 'react-router-dom';
import PointsAndBonus from '../pointsAndBonus';
import TargetManage from '../targetManage';
import SubOrdinate from '../subOrdinate';
import {
  AppContainer, Header, ContentContainer, HeaderLi,
} from './style';

function App() {
  const history = useHistory();
  const dispatch = useDispatch();
  const { path } = useRouteMatch();
  const navbarList = useSelector((state: any) => state.getIn(['App', 'navbarList']));

  function handleClickNavBarItem(i: {
    id: number;
    title: string;
    get: Function;
    url: string;
  }) {
    const toRoute = i.get('url');
    const updatedList = navbarList.map(
      (item: { id: number; title: string; get: Function; set: Function }) => {
        if (item.get('id') === i.get('id')) {
          return item.set('active', true);
        }
        return item.set('active', false);
      },
    );
    dispatch({
      type: 'updateNavBarList',
      value: updatedList,
    });
    history.push({
      pathname: toRoute,
    });
  }
  return (
    <AppContainer>
      <Header>
        {navbarList.map(
          (item: { id: number; title: string; get: Function; url: string, active: boolean }) => (
            <HeaderLi
              onClick={() => handleClickNavBarItem(item)}
              key={item.get('id')}
              active={item.get('active')}
            >
              {item.get('title')}
            </HeaderLi>
          ),
        )}
      </Header>

      <ContentContainer>
        <Switch>
          <Route path={`${path}/pointsAndBonus`}>
            <PointsAndBonus />
          </Route>
          <Route path={`${path}/targetManagment`}>
            <TargetManage />
          </Route>
          <Route path={`${path}/subOrdinate`}>
            <SubOrdinate />
          </Route>
          <Route path={`${path}`}>
            <Redirect to={{
              pathname: `${path}/pointsAndBonus`,
            }}
            />
          </Route>
        </Switch>
      </ContentContainer>
    </AppContainer>
  );
}

export default App;
